# -*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class AccountChartTemplate(models.Model):
    _inherit = "account.chart.template"

    @api.multi
    def generate_salary(self, acc_template_ref, company):
        self.ensure_one()
        
        # update salary rule account
        account_salary_tax    = acc_template_ref.get(self.property_account_salary_tax_id.id)
        account_other_payable = acc_template_ref.get(self.property_account_other_payable_id.id)
        
        rules = self.env['hr.salary.rule'].search([('company_id','=', company.id)])

        socials = rules.filtered(lambda item: item.code in ['SOCIAL','SOCIAL.COMP'] )
        for social in socials:
            social.account_debit = account_other_payable
        
        tax = rules.filtered(lambda item: item.code == 'TAX' )
        tax.account_debit = account_salary_tax
        
        net = rules.filtered(lambda item: item.code == 'NET' )
        net.account_credit = account_other_payable

    @api.multi
    def _load_template(self, company, code_digits=None, account_ref=None, taxes_ref=None):
        account_ref, taxes_ref = super(AccountChartTemplate, self)._load_template(
            company, code_digits, account_ref, taxes_ref)
        
        # generate salary rule function
        self.generate_salary(account_ref, company)
        return account_ref, taxes_ref


    @api.multi
    def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None):
        """Create the tax_cash_basis_journal_id"""
        res = super(AccountChartTemplate, self)._prepare_all_journals(
            acc_template_ref, company, journals_dict=journals_dict)
        
        #if not self == self.env.ref('l10n_cn_smb_2019.l10n_chart_china_small_business'):
        #    return res
        
        account = acc_template_ref.get(self.property_account_salary_id.id)

        res.append({
            'type': 'general',
            'name': _('薪资账簿'),
            'internal_code': 'salary',
            'code': 'SLRY',
            'company_id': company.id,
            'default_credit_account_id': account,
            'default_debit_account_id': account,
            'show_on_dashboard': True,
        })
        return res



class HrContract(models.Model):
    _inherit = 'hr.contract'


    @api.model
    def _get_default_journal(self):
        journal = self.env['account.journal'].search([
                ('internal_code','=','salary'), ('type','=','general')],limit=1)

        return journal

    journal_id = fields.Many2one(
        'account.journal', 'Salary Journal', default = _get_default_journal )

